//
//  LoadingViewController.m
//  Telemedicine
//
//  Created by Trong Ton on 6/25/14.
//  Copyright (c) 2014 Trong Ton. All rights reserved.
//

#import "LoadingViewController.h"
#import "JMImageCache.h"

#define DEFAULT_BLUE [UIColor colorWithRed:51.0/255.0 green:181.0/255.0 blue:229.0/255.0 alpha:1.0]

@interface LoadingViewController ()

@end

@implementation LoadingViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    NSArray *vComp = [[UIDevice currentDevice].systemVersion componentsSeparatedByString:@"."];
    int startYView = ([[vComp objectAtIndex:0] intValue] >= 7)?20:0;
    backgroundLoading = [[UIImageView alloc]initWithFrame:CGRectMake(0, startYView, self.view.bounds.size.width, self.view.bounds.size.height - startYView)];
    backgroundLoading.contentMode = UIViewContentModeScaleAspectFit;
    NSString *linkImage = [[NSUserDefaults standardUserDefaults] objectForKey:@"LoadingImageLink"];
    UIImage *image = [UIImage imageNamed:@"default_welcome.jpg"];
    if (linkImage && linkImage.length > 0) {
        image = [[JMImageCache sharedCache] loadImageForURL:[NSURL URLWithString:linkImage]];
    }
    image = [self editImage:image screenWidth:backgroundLoading.bounds.size];
    backgroundLoading.image = image;
    [self.view addSubview:backgroundLoading];
    [backgroundLoading release];
    
    if(kTestVersion) {
        UIButton *resetButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        resetButton.backgroundColor = [UIColor whiteColor];
        resetButton.frame = CGRectMake(self.view.bounds.size.width - 90, 50, 70, 30);
        [resetButton setTitle:@"Clear Data" forState:UIControlStateNormal];
        resetButton.titleLabel.font = [UIFont systemFontOfSize:12];
        [resetButton addTarget:self action:@selector(clearData:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:resetButton];
        
        NSString *codeString = [[NSUserDefaults standardUserDefaults] objectForKey:@"code"];
        
        UILabel *codeLogin = [[UILabel alloc] initWithFrame:CGRectMake(self.view.bounds.size.width - 90, 90, 70, 30)];
        codeLogin.backgroundColor = [UIColor whiteColor];
        codeLogin.font = [UIFont systemFontOfSize:12];
        if (codeString && codeString.length > 0) {
            codeLogin.text = codeString;
        }
        [self.view addSubview:codeLogin];
        [codeLogin release];
        
    }
    
    
    progressView = [[THProgressView alloc] initWithFrame:CGRectMake(20, [[UIScreen mainScreen] bounds].size.height - 150, 280, 20)];
    progressView.borderTintColor = DEFAULT_BLUE;
    progressView.progressTintColor = DEFAULT_BLUE;
    [self.view addSubview:progressView];
    [progressView release];
    
    UILabel *loadingLabel = [[UILabel alloc] initWithFrame:CGRectMake(40, [[UIScreen mainScreen] bounds].size.height - 125, 260, 20)];
    loadingLabel.backgroundColor = [UIColor clearColor];
    loadingLabel.font = [UIFont boldSystemFontOfSize:16];
    loadingLabel.text = @"Loading...";
    loadingLabel.textColor = DEFAULT_BLUE;
    [self.view addSubview:loadingLabel];
    [loadingLabel release];
    
    [self getImageForView];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    //[self performSelector:@selector(removeLoading) withObject:nil afterDelay:3.0];
    timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(updateProgress) userInfo:nil repeats:YES];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (UIImage *)editImage:(UIImage *)_image screenWidth:(CGSize)bound {
    
    UIGraphicsBeginImageContextWithOptions(bound, NO, 2.0);
    
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    CGContextSetFillColorWithColor(context, [UIColor whiteColor].CGColor);
    CGContextFillRect(context, CGRectMake(0.0, 0.0, bound.width, bound.height));
    float scale = bound.width/_image.size.width;
    NSLog(@"bound.width = %f, image.width = %f with scale = %f", bound.width, _image.size.width, scale);
    CGRect imageRect = CGRectMake(0, 0, _image.size.width * scale, _image.size.height * scale);
    
    [_image drawInRect:imageRect];
    
    UIImage * resizedImage = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    return resizedImage;
}


- (void)removeLoading {
    [[AppDelegate sharedDelegate] addCallDoctorView];
}

- (void)updateProgress {
    passTime += (0.1 / 3.0);
    [progressView setProgress:passTime];
    if(passTime > 1.05) {
        [timer invalidate];
        timer = nil;
        [self removeLoading];
    }
//    [self.progressViews enumerateObjectsUsingBlock:^(THProgressView *progressView, NSUInteger idx, BOOL *stop) {
//        [progressView setProgress:self.progress animated:YES];
//    }];
}

- (void)clearData:(id)sender {
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"code"];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"wasLogin"];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"TermsWasCheck"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

- (void)getImageForView {
    //https://wp-dot-erudite-stratum-347.appspot.com/ws-media
    //Type 1: welcome, splash screen
    //Type 2: background image
    //Type 3, 4, 5, 6: Press to call doctor button
    APIsBaseService *serVice = [APIsBaseService service];
    [serVice requestWithURL:@"ws-media"
                     params:nil
               successBlock:^(NSDictionary *dictionary){
                   NSArray *arrays = [dictionary objectForKey:@"docs"];
                   if(arrays && [arrays count] > 0) {
                       for (int i = 0; i < [arrays count]; i++) {
                           NSString *linkString = [[arrays objectAtIndex:i] objectForKey:@"guid"];
                           int type = [[[arrays objectAtIndex:i] objectForKey:@"media_type"] intValue];
                           if (type == 1 && linkString != nil && linkString.length > 0) {
                               [[NSUserDefaults standardUserDefaults] setObject:linkString forKey:@"LoadingImageLink"];
                               [[NSUserDefaults standardUserDefaults] synchronize];
//                               [backgroundLoading setImageWithURL:[NSURL URLWithString:linkString] placeholder:[UIImage imageNamed:@"default_welcome.jpg"]];
                               if (linkString && linkString.length > 0) {
                                   UIImage *image = [[JMImageCache sharedCache] loadImageForURL:[NSURL URLWithString:linkString]];
                                   image = [self editImage:image screenWidth:backgroundLoading.bounds.size];
                                   backgroundLoading.image = image;
                               }
                               
                           }
                           else if (type == 2 && linkString != nil && linkString.length > 0) {
                               [[NSUserDefaults standardUserDefaults] setObject:linkString forKey:@"BackgroundImageLink"];
                               [[NSUserDefaults standardUserDefaults] synchronize];
                           }
                           else  if (type == 3 && linkString != nil && linkString.length > 0) {
                               [[NSUserDefaults standardUserDefaults] setObject:linkString forKey:@"FirstButtonImageLink"];
                               [[NSUserDefaults standardUserDefaults] synchronize];
                           }
                           else if (type == 4 && linkString != nil && linkString.length > 0) {
                               [[NSUserDefaults standardUserDefaults] setObject:linkString forKey:@"SecondButtonImageLink"];
                               [[NSUserDefaults standardUserDefaults] synchronize];
                           }
                           else  if (type == 5 && linkString != nil && linkString.length > 0) {
                               [[NSUserDefaults standardUserDefaults] setObject:linkString forKey:@"ThreeButtonImageLink"];
                               [[NSUserDefaults standardUserDefaults] synchronize];
                           }
                           else if (type == 6 && linkString != nil && linkString.length > 0) {
                               [[NSUserDefaults standardUserDefaults] setObject:linkString forKey:@"FourBroundImageLink"];
                               [[NSUserDefaults standardUserDefaults] synchronize];
                           }
                       }
                   }
                   else {
                       
                   }
               }
                 errorBlock:^(NSError *error){
                     
                 }
                 httpMethod:@"GET"];
}

@end
